//*****************************************************************************
// JFab (http://code.google.com/p/jfab)
// Copyright (c) 2011-2012 JFab.org
// Admin jfab@jeffreythompson.net
//
// See the file "LICENSE.txt" for information on usage and redistribution of
// this file, and for a DISCLAIMER OF ALL WARRANTIES.
//*****************************************************************************

package org.jfab.swingui.util;

import java.awt.Component;

/**
 * Provides a thread that waits until a component is realized, then performs a
 * specified action. The action is specified by a subclass overriding the method
 * <code>realized()</code>.
 */
public abstract class RealizedThread extends Thread
{
    /** The component we're waiting on. */
    protected Component _component;

    /** The sleep time between checks in milliseconds. */
    private int _sleepTimeMillis = 100;

    /**
     * This method gets called when the component is realized.
     * 
     * @param component Component.
     */
    public RealizedThread(final Component component)
    {
        _component = component;
    }

    /**
     * This method gets called when the component is realized.
     * 
     * @param component Component.
     * @param sleepTimeMillis Sleep time in milliseconds.
     */
    public RealizedThread(final Component component, final int sleepTimeMillis)
    {
        _component = component;
        _sleepTimeMillis = sleepTimeMillis;
    }

    /**
     * Action to perform when the component is realized. Subclasses need to
     * override this method.
     */
    public abstract void realized();

    /**
     * Wait for the component to be realized, the call <code>realized()</code>.
     */
    @Override
    public void run()
    {
        while (true)
        {
            final java.awt.Dimension size = _component.getSize();

            if ((size.width == 0) && (size.height == 0))
            {
                try
                {
                    sleep(_sleepTimeMillis);
                }
                catch (final InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
            else
            {
                realized();

                return;
            }
        }
    }
}
